from fastapi import APIRouter, Query,UploadFile
from tortoise.expressions import Q

from app.controllers.customers.customers_follow import customers_follow_controller
from app.controllers.system.user import user_controller
from app.models import Customers, CustomersFollow
from app.settings.config import settings
from app.controllers.customers.customers_list  import customers_controller
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.customers import CustomersCreate, CustomersUpdate, CustomersFollowCreate
from app.utils.upload import upload_image
from app.core.ctx import CTX_USER_ID

customers_user_router = APIRouter()
model_name = "表单"



@customers_user_router.post("/create_user", summary=f"创建{model_name}")
async def do_create(
        category_in: CustomersCreate,
):
    customers_data = await Customers.filter(qymc=category_in.qymc).first()
    if customers_data:
        return Fail(msg="已经提交过了,请勿重复提交")

    await customers_controller.do_create(obj_in=category_in)
    return Success(msg="创建成功")

@customers_user_router.post("/file_user", summary="上传图片")
async def do_file(file: UploadFile):
    url = await upload_image(file,"customers")
    if not url:
        return Fail(code=400, msg="图片格式错误")
    data = {"url": url}
    return Success(data=data)

@customers_user_router.post("/create_f", summary=f"额度查询")
async def do_create(
        category_in: CustomersFollowCreate,
):
    ##开始查询公司名称
    qymc = category_in.qymc
    customer_data = await Customers.filter(qymc=qymc).first().values("price","status")
    if customer_data:
        price = customer_data["price"]
        status = customer_data["status"]
        if status==0:
            return Fail(msg="暂未出结果,请耐心等待或者联系您的客户经理！")
        else:
            customers_follow_data = await CustomersFollow.filter(qymc=qymc).first()
            if not customers_follow_data:
                await customers_follow_controller.do_create(obj_in=category_in)
            return Success(msg=price)
    else:
        return Fail(msg="系统未查询到该企业，详情请联系您的客户经理")

